<style lang="less">
    @import './own-space.less';
</style>

<template>
    <div>
        <Card>
            <p slot="title">
                <Icon type="person"></Icon>
                个人信息
            </p>
            <div>
              <Form
                ref="userForm"
                :model="userForm"
                :label-width="100"
                label-position="right"
                :rules="inforValidate"
              >
                <FormItem label="用户名称：" prop="userName">
                  <div style="display:inline-block;width:300px;">
                    <i-input v-model="userForm.userName" :disabled="true"></i-input>
                  </div>
                </FormItem>
                <FormItem label="真实姓名：" prop="realName">
                  <div style="display:inline-block;width:300px;">
                    <i-input v-model="userForm.realName"></i-input>
                  </div>
                </FormItem>
                <FormItem label="用户手机：" prop="phone">
                  <div style="display:inline-block;width:300px;">
                    <i-input v-model="userForm.phone" placeholder="暂未填写手机号"></i-input>
                  </div>
                </FormItem>
                <FormItem label="邮箱：">
                  <div style="display:inline-block;width:300px;">
                    <i-input v-model="userForm.email" placeholder="暂未填写邮箱"></i-input>
                  </div>
                </FormItem>
                <FormItem label="登录密码：">
                  <a href="javascript:void(0)" @click="showEditPassword">修改密码</a>
                </FormItem>
                <!--<FormItem label="个人头像：">-->
                  <!--<Upload-->
                    <!--ref="upload"-->
                    <!--:show-upload-list="false"-->
                    <!--:default-file-list="defaultList"-->
                    <!--:on-success="handleSuccess"-->
                    <!--:format="['jpg','jpeg','png']"-->
                    <!--:max-size="2048"-->
                    <!--:on-format-error="handleFormatError"-->
                    <!--:on-exceeded-size="handleMaxSize"-->
                    <!--:before-upload="handleBeforeUpload"-->
                    <!--multiple-->
                    <!--type="drag"-->
                    <!--action="../api/systemmanage/userCenter/fileUpload"-->
                    <!--style="display: inline-block;width:58px;">-->
                    <!--<img :src="headAppearSrc"/>-->
                    <!--<div style="width: 58px;height:58px;line-height: 58px;">-->
                      <!--<Icon type="ios-camera" size="20"></Icon>-->
                    <!--</div>-->
                  <!--</Upload>-->
                <!--</FormItem>-->
                <div>
                  <Button type="text" style="width: 100px;" @click="cancelEditUserInfor">取消</Button>
                  <Button type="primary" style="width: 100px;" :loading="save_loading" @click="saveEdit">保存
                  </Button>
                </div>
              </Form>
            </div>
        </Card>
        <Modal v-model="editPasswordModal" :closable='false' title="修改密码" :mask-closable=false :width="500">
            <Form ref="editPasswordForm" :model="editPasswordForm" :label-width="100" label-position="right"
                  :rules="passwordValidate">
                <FormItem label="原密码" prop="oldPass">
                    <i-input v-model="editPasswordForm.oldPass" placeholder="请输入初始密码"></i-input>
                </FormItem>
                <FormItem label="新密码" prop="newPass">
                    <i-input v-model="editPasswordForm.newPass" placeholder="请输入新密码，至少5位字符"></i-input>
                </FormItem>
                <FormItem label="确认新密码" prop="rePass">
                    <i-input v-model="editPasswordForm.rePass" placeholder="请再次输入新密码"></i-input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="cancelEditPass">取消</Button>
                <Button type="primary" :loading="savePassLoading" @click="saveEditPass">保存</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
  import Cookies from 'js-cookie';
  export default {
    data() {
      const validePhone = (rule, value, callback) => {
        var re = /^1[0-9]{10}$/;
        if (!re.test(value)) {
          callback(new Error('请输入正确格式的手机号'));
        } else {
          callback();
        }
      };
      const valideRePassword = (rule, value, callback) => {
        if (value !== this.editPasswordForm.newPass) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      };
      return {
        userForm: {
          userName: '',
          realName: '',
          phone: '',
          email: '',
          headAppear: ''
        },
        uid: '',  // 登录用户的userId
        securityCode: '',  // 验证码
        phoneHasChanged: false,  // 是否编辑了手机
        save_loading: false,
        identifyError: '',  // 验证码错误
        editPasswordModal: false, // 修改密码模态框显示
        savePassLoading: false,
        oldPassError: '',
        identifyCodeRight: false,  // 验证码是否正确
        hasGetIdentifyCode: false,  // 是否点了获取验证码
        canGetIdentifyCode: false,  // 是否可点获取验证码
        checkIdentifyCodeLoading: false,
        inforValidate: {
          name: [
            {required: true, message: '请输入姓名', trigger: 'blur'}
          ],
          cellphone: [
            {required: true, message: '请输入手机号码'},
            {validator: validePhone}
          ]
        },
        editPasswordForm: {
          oldPass: '',
          newPass: '',
          rePass: ''
        },
        passwordValidate: {
          oldPass: [
            {required: true, message: '请输入原密码', trigger: 'blur'}
          ],
          newPass: [
            {required: true, message: '请输入新密码', trigger: 'blur'},
            {min: 5, message: '请至少输入6个字符', trigger: 'blur'},
            {max: 32, message: '最多输入32个字符', trigger: 'blur'}
          ],
          rePass: [
            {required: true, message: '请再次输入新密码', trigger: 'blur'},
            {validator: valideRePassword, trigger: 'blur'}
          ]
        },
        inputCodeVisible: false, // 显示填写验证码box
        initPhone: '',
        gettingIdentifyCodeBtnContent: '获取验证码' , // “获取验证码”按钮的文字
        defaultList: []
      };
    },
    methods: {
      headAppearSrc() {
        return this.userForm.headAppear;
      },
      showEditPassword() {
        this.editPasswordModal = true;
      },
      cancelEditUserInfor() {
        this.$store.commit('removeTag', 'ownspace_index');
        localStorage.pageOpenedList = JSON.stringify(this.$store.state.app.pageOpenedList);
        let lastPageName = '';
        if (this.$store.state.app.pageOpenedList.length > 1) {
          lastPageName = this.$store.state.app.pageOpenedList[1].name;
        } else {
          lastPageName = this.$store.state.app.pageOpenedList[0].name;
        }
        this.$router.push({
          name: lastPageName
        });
      },
      cancelEditPass() {
        this.editPasswordModal = false;
      },
      saveEditPass() {
        this.$refs['editPasswordForm'].validate((valid) => {
          if (valid) {
            // 改密码
            this.savePassLoading = true;
            this.savePassword()
          }
        });
      },
      savePassword(){
        let user = this.userForm;
        let obj = {
          userName: user.userName,
          oldPassword: this.editPasswordForm.oldPass,
          newPassword: this.editPasswordForm.newPass
        };
        $.ajax('../api/systemmanage/userCenter/updateUserPasssword', {
          method: "post",
          contentType: "application/json;charset=utf-8",
          data: JSON.stringify(obj),
          success: (data) => {
            this.editPasswordForm = {
              oldPass: '',
              newPass: '',
              rePass: ''
            };
            if (data.code === 200) {
              this.$Notice.success({
                title: data.data,
              });
              this.editPasswordModal = false
            } else {
              this.$Notice.error({
                title: data.data,
              });
            }
            this.savePassLoading = false
          }
        })
      },
      init() {
        this.userForm.realName = Cookies.get('realName');
        this.userForm.userName = Cookies.get('user');
        this.userForm.phone = Cookies.get('phone');
        this.userForm.email = Cookies.get('email');
        this.userForm.headAppear = Cookies.get('setAvator');
      },
      saveEdit(){
        let user = this.userForm;
        let obj = {
          userName: user.userName,
          realName: user.realName,
          email: user.email,
          phone: user.phone
        };
        $.ajax('../api/systemmanage/userCenter/updateUserInfo', {
          method: "post",
          contentType: "application/json;charset=utf-8",
          data: JSON.stringify(obj),
          success: (data) => {
            if (data.code === 200) {
              this.$Notice.success({
                title: data.data,
              });
              Cookies.set('user', user.userName);
              Cookies.set('phone', user.phone);
              Cookies.set('realName', user.realName);
              Cookies.set('email', user.email);
              Cookies.set('setAvator', user.headAppear);
            } else {
              this.$Notice.error({
                title: data.data,
              });
            }
          }
        })
      },
    },
    mounted() {
      this.init();
    }
  };
</script>
